package com.huluobo.a2204monthdemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2204monthdemo.MainActivity
import com.huluobo.a2204monthdemo.R
import com.huluobo.a2204monthdemo.databinding.ActivityLoginBinding
import com.huluobo.a2204monthdemo.register.RegisterActivity
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                SPUtils.getInstance().put(Const.PARAM_TOKEN, it.data.token)
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "登录失败:$it")
        }
    }

    override fun initView() {

        dataBinding.loginBtn.setOnClickListener {
            val usernameString = dataBinding.loginUsername.text.toString()
            val passwordString = dataBinding.loginPassword.text.toString()
            if (usernameString.isNotEmpty() && passwordString.isNotEmpty()) {
                viewModel.login(
                    usernameString,
                    passwordString
                )
            } else {
                dataBinding.loginUsername.error = "用户名密码不能为空"
            }
        }

        dataBinding.loginToRegister.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_login
}